#coding=utf-8

from re import T
import socket
from threading import Thread
from random import choice
import random
import signal
import time

class UdpSender(object):

    def __init__(self, peerip, peerport = 0, bind='0.0.0.0', bindport=20000, threadnum = 4):
        self.bind = bind
        self.bindport = bindport
        self.threadnum = 8
        self.peerip = peerip
        self.peerport = peerport
        signal.signal(signal.SIGINT, self.signalHandler)
        self.SIGNAL_SIGINT = 0
        self.randomstr = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()'

    def signalHandler(self, signum, frame):
        print('signalHandler----------')
        self.SIGNAL_SIGINT = 1

    def getBindPort(self):
        if self.bindport == 0:
            return random.uniform(0, 65535)
        return self.bindport

    def genPacket(self):
        packet = ''
        for i in range(1473):
            lin = choice(self.randomstr)
            packet = packet + lin
        return packet

    def safeSend(self, sock, packet, peerip, peerport):
        try:
            sock.sendto(packet, (peerip, peerport))
        except Exception as ex:
            print('ex', ex)

    def at(self, bindport):
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.bind((self.bind, bindport))
        packet = self.genPacket()
        while 1:
            if self.SIGNAL_SIGINT == 1:
                return
            if self.peerport == 0:
                for i in range(65535):
                    self.safeSend(s, packet, self.peerip, i)
            else:
                self.safeSend(s, packet, self.peerip, self.peerport)

    def run(self):
        threadList = []
        for i in range(self.threadnum):
            t = Thread(target=self.at, args=(self.getBindPort() + i,))
            t.start()
            threadList.append(t)
        while 1:
            if self.SIGNAL_SIGINT == 1:
                return
            time.sleep(5)

ua = UdpSender(peerip='172.16.27.127', peerport=8011, threadnum=8)
ua.run()